"""
This script runs the application using a development server.
It contains the definition of routes and views for the application.
"""
from dataclasses import dataclass
from flask import Flask
from flask import request
from flask import render_template
from flask import jsonify
from flask import g
from flask import redirect
from flask import session
import utils
import pymysql
import traceback

app = Flask(__name__)

# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app


@app.before_request
def before_requset():
    g.user = None


@app.route('/time')
def get_time():
    return utils.get_time()


#  默认访问dist-dev 下的 index.html 页面
@app.route('/')
def index():
    return render_template("index.html")

# 用户登录
@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        user = request.form.get('username')
        pwd = request.form.get('password')
        dam = utils.get_login(user, pwd)[0]
        grad = utils.get_login(user, pwd)[1]
        print(dam)
        if (dam == 1):
            return jsonify({'code': 200, 'msg': '登录成功', 'data': grad})
        else:
            return jsonify({'code': 201, 'msg': '用户名或密码错误，请重试'})


@app.route('/out', methods=['GET', 'POST'])
def login_out():
    # session.clear()
    return redirect('/')


@app.route('/get_adm', methods=['POST'])
def get_adm():
    res = utils.get_adm()
    temp = {}
    result = []
    if (res != None):
        for i in res:
            temp['id'] = i[0]
            temp['name'] = i[1]
            temp['grade'] = i[3]
            result.append(temp.copy())
        return jsonify({'code': 200, 'msg': '', 'data': result})


@app.route('/get_sup', methods=['POST'])
def get_sup():
    res = utils.get_sup()
    temp = {}
    result = []
    if (res != None):
        for i in res:
            temp['id'] = i[0]
            temp['name'] = i[1]
            temp['agent'] = i[2]
            temp['telephone'] = i[3]
            temp['address'] = i[4]
            result.append(temp.copy())
        return jsonify(result)


@app.route('/get_cus', methods=['POST'])
def get_cus():
    res = utils.get_cus()
    temp = {}
    result = []
    if (res != None):
        for i in res:
            temp['id'] = i[0]
            temp['name'] = i[1]
            temp['telephone'] = i[2]
            temp['address'] = i[3]
            result.append(temp.copy())
        return jsonify(result)


@app.route('/get_sto', methods=['POST'])
def get_sto():
    res = utils.get_sto()
    temp = {}
    result = []
    if (res != None):
        for i in res:
            temp['id'] = i[0]
            temp['name'] = i[1]
            temp['describe'] = i[2]
            result.append(temp.copy())
        return jsonify(result)


@app.route('/add_adm', methods=['POST'])
def add_adm():
    if request.method == 'POST':
        username = request.form.get("username")
        password = request.form.get("password")
        grade = request.form.get("grade")
        res = utils.add_adm(username, password, grade)
        return jsonify({'code': 200, 'msg': '', 'data': res})


@app.route('/dele_adm', methods=['POST'])
def dele_adm():
    if request.method == 'POST':
        username = request.form.get("username")
        if (username != 'root'):
            res = utils.dele_adm(username)
        else:
            res = 'root'
        return res

@app.route('/updt_adm', methods=['POST'])
def updt_adm():
    if request.method == 'POST':
        userID = request.form.get("userID")
        username = request.form.get("username")
        password1 = request.form.get("password1")
        password2 = request.form.get("password2")
        grade = request.form.get("grade")
        if (username == 'root'):
            res = 'root'
            return res
        if (password1 == password2):
            res = utils.updt_adm(userID, username, password1, grade)
            return res
        else:
            return "psd_f"

# 创建任务
@app.route('/task_add', methods=['POST'])
def task_add():
    if request.method == 'POST':
        name = request.form.get("name")
        describe = request.form.get("describe")
        deadline = request.form.get("deadline")
        res = utils.task_add(name, describe, deadline)
        return jsonify({'code': 200, 'msg': '', 'data': res})

# 编辑任务
@app.route('/task_edit', methods=['POST'])
def task_edit():
    if request.method == 'POST':
        id = request.form.get("id")
        name = request.form.get("name")
        describe = request.form.get("describe")
        deadline = request.form.get("deadline")
        status = request.form.get("status")
        res = utils.task_edit(int(id), name, describe, deadline, status)
        return jsonify({'code': 200, 'msg': '', 'data': res})


# 查询任务列表
@app.route("/task_get", methods=['POST'])
def task_get():
    if request.method == 'POST':
        res = utils.task_get()
        temp = {}
        result = []
        if (res != None):
            for i in res:
                temp['id'] = i[0]
                temp['name'] = i[1]
                temp['describe'] = i[2]
                # 时间转换成 年月日时分秒
                temp['create_time'] = i[3].strftime('%Y-%m-%d %H:%M:%S')
                temp['deadline'] = i[4].strftime('%Y-%m-%d %H:%M:%S')
                temp['status'] = i[5]
                result.append(temp.copy())
        return jsonify({'code': 200, 'msg': '', 'data': result})

# 根据任务id查询任务详情
@app.route("/task_get_id", methods=['POST'])
def task_get_id():
    if request.method == 'POST':
        id = request.form.get("id")
        res = utils.task_get_id(int(id))
        temp = {}
        result = []
        if (res != None):
            for i in res:
                temp['id'] = i[0]
                temp['name'] = i[1]
                temp['describe'] = i[2]
                # 时间转换成 年月日时分秒
                temp['create_time'] = i[3].strftime('%Y-%m-%d %H:%M:%S')
                temp['deadline'] = i[4].strftime('%Y-%m-%d %H:%M:%S')
                temp['status'] = i[5]
                result.append(temp.copy())
        return jsonify({'code': 200, 'msg': '', 'data': result[0]})

# 删除任务
@app.route('/task_del', methods=['POST'])
def task_del():
    if request.method == 'POST':
        id = request.form.get("id")
        res = utils.task_del(int(id))
        return jsonify({'code': 200, 'msg': '', 'data': res})


if __name__ == '__main__':
    import os

    HOST = os.environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(os.environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    app.run(HOST, PORT)
